import { ref, onMounted, onUnmounted } from 'vue';

type MessageHandler = (data: any) => void;

export function useWebSocket(url: string) {
  const socket = ref<WebSocket | null>(null);
  const isConnected = ref(false);
  const messageHandlers = new Set<MessageHandler>();

  const connect = () => {
    return new Promise<void>((resolve, reject) => {
      socket.value = new WebSocket(url);

      socket.value.onopen = () => {
        isConnected.value = true;
        console.log('WebSocket connected');
        resolve();
      };

      (socket.value as WebSocket).onmessage = (event) => {
        try {
          //   const data = JSON.parse(event.data);
          messageHandlers.forEach((handler) => handler(event.data));
        } catch (error) {
          console.error('Error parsing WebSocket message:', error);
        }
      };

      socket.value.onclose = () => {
        isConnected.value = false;
        console.log('WebSocket disconnected');
      };

      socket.value.onerror = (error) => {
        console.log('WebSocket error:', error);
        reject(error);
      };
    });
  };

  const disconnect = () => {
    if (socket.value) {
      isConnected.value = false;
      socket.value.close();
      socket.value = null;
    }
  };

  const send = (data: any) => {
    if (socket.value && isConnected.value) {
      //   socket.value.send(JSON.stringify(data));
      socket.value.send(data);
    } else {
      console.error('WebSocket is not connected');
    }
  };

  const addMessageHandler = (handler: MessageHandler) => {
    messageHandlers.add(handler);
  };

  const deleteMessageHandler = () => {
    messageHandlers.clear();
  };

  return {
    socket,
    isConnected,
    connect,
    disconnect,
    send,
    addMessageHandler,
    deleteMessageHandler,
  };
}
